﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "角色权限管理";
    Layout = null;
}

<!-- 先加载CSS -->
<link href="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/css/layui.min.css" rel="stylesheet">

<div class="layui-container">
    <div class="layui-row">
        <div class="layui-col-md12">
            <h2>角色权限管理</h2>
        </div>
    </div>
    
    <div class="layui-row layui-col-space15">
        <!-- 左侧角色权限树 -->
        <div class="layui-col-md4">
            <div class="layui-card">
                <div class="layui-card-header">权限树</div>
                <div class="layui-card-body">
                    <div id="permissionTree"></div>
                </div>
            </div>
        </div>
        
        <!-- 右侧角色权限表格 -->
        <div class="layui-col-md8">
            <div class="layui-card">
                <div class="layui-card-header">
                    <button class="layui-btn" id="addRolePermissionBtn">添加角色权限</button>
                </div>
                <div class="layui-card-body">
                    <table id="rolePermissionTable" lay-filter="rolePermissionTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 弹窗表单模板 -->
<script type="text/html" id="addRolePermissionFormTpl">
    <form id="addRolePermissionForm" class="layui-form" style="margin:20px 20px 0 0;">
        <div class="layui-form-item">
            <label class="layui-form-label">选择角色</label>
            <div class="layui-input-block">
                <select name="RoleId" lay-verify="required" id="roleSelect">
                    <option value="">请选择角色</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">选择权限</label>
            <div class="layui-input-block" id="permissionCheckboxes" style="border:1px solid #ccc;padding:10px;max-height:200px;overflow:auto;"></div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="addRolePermission">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary" id="resetBtn">重置</button>
            </div>
        </div>
    </form>
</script>

<!-- 先加载jQuery，再加载Layui -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.min.js"></script>

<script>
    // 确保DOM和Layui都加载完成后再执行
    $(document).ready(function() {
        console.log('DOM加载完成，开始初始化Layui');

        layui.use(['table', 'layer', 'form', 'tree'], function() {
            var table = layui.table;
            var layer = layui.layer;
            var form = layui.form;
            var tree = layui.tree;
            var $ = layui.$;

            console.log('Layui模块加载完成');
            
            // 加载权限树
            function loadPermissionTree() {
                console.log('开始加载权限树');
                $.ajax({
                    url: '/RolePermission/GetRolePermissionTree',
                    type: 'GET',
                    success: function(res) {
                        console.log('权限树数据:', res);
                        if(res.code === 0 && res.data) {
                            // 转换数据格式以适配layui tree
                            var treeData = res.data.map(function(item) {
                                return convertToTreeNode(item);
                            });
                            
                            console.log('转换后的树数据:', treeData);
                            
                            // 渲染树
                            tree.render({
                                elem: '#permissionTree',
                                data: treeData,
                                showCheckbox: false,
                                showLine: true,
                                accordion: false,
                                onlyIconControl: false,
                                click: function(obj) {
                                    console.log('点击的节点:', obj);
                                    // 可以根据需求在点击节点时执行操作
                                }
                            });
                        } else {
                            layer.msg('加载权限树失败：' + (res.msg || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        console.error('加载权限树错误:', xhr);
                        layer.msg('加载权限树失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                    }
                });
            }
            
            // 递归转换树节点格式
            function convertToTreeNode(node) {
                var treeNode = {
                    id: node.id,
                    title: node.label,
                    spread: false
                };
                
                if(node.children && node.children.length > 0) {
                    treeNode.children = node.children.map(function(child) {
                        return convertToTreeNode(child);
                    });
                }
                
                return treeNode;
            }
            
            // 初始化表格
            table.render({
                elem: '#rolePermissionTable',
                url: '/RolePermission/QueryRolePermission',
                page: true,
                cols: [[
                    {field: 'id', title: 'ID', sort: true},
                    {field: 'roleName', title: '角色名称'},
                    {field: 'permissionName', title: '权限名称'},
                    {fixed: 'right', title: '操作', toolbar: '#rolePermissionTableBar', width:120}
                ]]
            });
            
            // 加载权限树
            loadPermissionTree();

            // 添加角色权限按钮点击事件
            $('#addRolePermissionBtn').on('click', function() {
                console.log('点击添加角色权限按钮');

                layer.open({
                    type: 1,
                    title: '添加角色权限',
                    area: ['500px', '400px'],
                    content: $('#addRolePermissionFormTpl').html(),
                    success: function(layero, index) {
                        console.log('弹窗打开成功');

                        // 加载角色
                        $.get('/RolePermission/QueryRole', function(res) {
                            console.log('角色数据:', res);
                            if(res && res.data) {
                                var select = layero.find('select[name="RoleId"]');
                                select.empty().append('<option value="">请选择角色</option>');
                                res.data.forEach(function(role) {
                                    select.append('<option value="' + role.id + '">' + role.roleName + '</option>');
                                });
                                form.render('select');
                            }
                        }).fail(function(xhr, status, error) {
                            console.error('加载角色失败:', error);
                            layer.msg('加载角色失败');
                        });

                        // 加载权限
                        $.get('/RolePermission/QueryPermission', function(res) {
                            console.log('权限数据:', res);
                            if(res && res.data) {
                                var permDiv = layero.find('#permissionCheckboxes');
                                permDiv.empty();
                                res.data.forEach(function(permission) {
                                    permDiv.append(
                                        '<input type="checkbox" name="PermissionIds" value="' + permission.id + '" title="' + permission.permissionName + '" lay-skin="primary">'
                                    );
                                });
                                form.render('checkbox');
                            }
                        }).fail(function(xhr, status, error) {
                            console.error('加载权限失败:', error);
                            layer.msg('加载权限失败');
                        });

                        // 表单提交
                        form.on('submit(addRolePermission)', function(data) {
                            console.log('表单提交事件触发');

                            var roleId = data.field.RoleId;
                            var permissionIds = [];

                            // 收集选中的权限ID
                            layero.find('input[name="PermissionIds"]:checked').each(function() {
                                permissionIds.push(parseInt($(this).val()));
                            });

                            console.log('角色ID:', roleId);
                            console.log('权限IDs:', permissionIds);

                            // 验证数据
                            if(!roleId) {
                                layer.msg('请选择角色');
                                return false;
                            }
                            if(permissionIds.length === 0) {
                                layer.msg('请选择至少一个权限');
                                return false;
                            }

                            // 构造符合CreateRolePermissionDto格式的数据
                            var requestData = {
                                RoleId: parseInt(roleId),
                                PermissionId: permissionIds
                            };

                            console.log('发送到后端的数据:', JSON.stringify(requestData));

                            // 发送请求
                            $.ajax({
                                url: '/RolePermission/AddRolePermission',
                                type: 'POST',
                                contentType: 'application/json; charset=utf-8',
                                data: JSON.stringify(requestData),
                                beforeSend: function() {
                                    console.log('开始发送请求...');
                                },
                                success: function(response) {
                                    console.log('请求成功:', response);
                                    if(response.success) {
                                        layer.msg('添加成功');
                                        layer.close(index);
                                        table.reload('rolePermissionTable');
                                    } else {
                                        layer.msg(response.message || '添加失败');
                                    }
                                },
                                error: function(xhr, status, error) {
                                    console.error('请求失败:', xhr, status, error);
                                    console.error('状态码:', xhr.status);
                                    console.error('响应头:', xhr.getAllResponseHeaders());

                                    var errorMessage = '添加失败';
                                    if (xhr.responseJSON) {
                                        console.error('响应JSON:', xhr.responseJSON);
                                        errorMessage = xhr.responseJSON.message || errorMessage;
                                        if (xhr.responseJSON.errors) {
                                            console.error('验证错误:', xhr.responseJSON.errors);
                                        }
                                    }
                                    if (xhr.responseText) {
                                        console.error('响应文本:', xhr.responseText);
                                    }

                                    layer.msg(errorMessage + '，请查看控制台了解详情');
                                }
                            });

                            return false;
                        });

                        // 重置按钮点击事件
                        layero.find('#resetBtn').on('click', function(e) {
                            e.preventDefault();
                            // 重置角色选择
                            layero.find('select[name="RoleId"]').val('');
                            // 取消所有权限复选框
                            layero.find('input[name="PermissionIds"]').prop('checked', false);
                            // 重新渲染表单
                            form.render();
                            layer.msg('已重置');
                            return false;
                        });
                    }
                });
            });

            // 监听工具条事件
            table.on('tool(rolePermissionTable)', function(obj){
                var data = obj.data;
                if(obj.event === 'edit'){
                    // 编辑弹窗
                    layer.open({
                        type: 1,
                        title: '编辑角色权限',
                        area: ['500px', '400px'],
                        content: $('#addRolePermissionFormTpl').html(),
                        success: function(layero, index) {
                            // 加载角色
                            $.get('/RolePermission/QueryRole', function(res) {
                                if(res && res.data) {
                                    var select = layero.find('select[name="RoleId"]');
                                    select.empty().append('<option value="">请选择角色</option>');
                                    res.data.forEach(function(role) {
                                        var selected = (role.id === data.roleId) ? 'selected' : '';
                                        select.append('<option value="' + role.id + '" '+selected+'>' + role.roleName + '</option>');
                                    });
                                    form.render('select');
                                }
                            });
                            // 先查详情，拿到当前行的权限ID
                            $.get('/RolePermission/GetRolePermission?roleId=' + data.roleId, function(detailRes) {
                                var checkedIds = [];
                                if (detailRes.success && detailRes.data) {
                                    checkedIds = detailRes.data.permissionIds || [];
                                }
                                // 再查所有权限
                                $.get('/RolePermission/QueryPermission', function(res) {
                                    console.log('权限数据:', res);
                                    if(res && res.data) {
                                        var permDiv = layero.find('#permissionCheckboxes');
                                        permDiv.empty();
                                        res.data.forEach(function(permission) {
                                            // 类型统一为字符串比较，防止类型不一致
                                            var checked = checkedIds.map(String).includes(String(permission.id)) ? 'checked' : '';
                                            permDiv.append(
                                                '<input type="checkbox" name="PermissionIds" value="' + permission.id + '" title="' + permission.permissionName + '" lay-skin="primary" ' + checked + '>'
                                            );
                                        });
                                        form.render('checkbox');
                                    }
                                }).fail(function(xhr, status, error) {
                                    console.error('加载权限失败:', error);
                                    layer.msg('加载权限失败');
                                });
                                // 表单提交
                                form.on('submit(addRolePermission)', function(formData) {
                                    var roleId = formData.field.RoleId;
                                    var permissionIds = [];
                                    // 正确收集选中的权限ID
                                    layero.find('input[name="PermissionIds"]:checked').each(function() {
                                        permissionIds.push(parseInt($(this).val()));
                                    });
                                    if(!roleId) {
                                        layer.msg('请选择角色');
                                        return false;
                                    }
                                    if(permissionIds.length === 0) {
                                        layer.msg('请选择至少一个权限');
                                        return false;
                                    }
                                    var requestData = {
                                        RoleId: parseInt(roleId),
                                        PermissionId: permissionIds,
                                        Id: data.id // 传递主键id用于后端区分
                                    };
                                    $.ajax({
                                        url: '/RolePermission/UpdateRolePermission',
                                        type: 'PUT',
                                        contentType: 'application/json; charset=utf-8',
                                        data: JSON.stringify(requestData),
                                        success: function(response) {
                                            if(response.success) {
                                                layer.msg('修改成功');
                                                layer.close(index);
                                                table.reload('rolePermissionTable');
                                            } else {
                                                layer.msg(response.message || '修改失败');
                                            }
                                        },
                                        error: function(xhr) {
                                            layer.msg('修改失败');
                                        }
                                    });
                                    return false;
                                });
                                // 重置按钮
                                layero.find('#resetBtn').on('click', function(e) {
                                    e.preventDefault();
                                    layero.find('select[name="RoleId"]').val('');
                                    layero.find('input[name="PermissionIds"]').prop('checked', false);
                                    form.render();
                                    layer.msg('已重置');
                                    return false;
                                });
                            });
                        }
                    });
                }
            });
        });
    });
</script>

<!-- 工具条模板 -->
<script type="text/html" id="rolePermissionTableBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
</script>

<style>
    /* 美化权限树 */
    #permissionTree {
        min-height: 400px;
        overflow: auto;
        padding: 10px;
    }
    
    /* 树节点样式 */
    .layui-tree-entry {
        padding: 6px 0;
    }
    
    .layui-tree-txt {
        color: #333;
        font-size: 14px;
    }
    
    /* 卡片样式 */
    .layui-card {
        margin-bottom: 15px;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }
    
    .layui-card-header {
        font-weight: bold;
        background-color: #f8f8f8;
    }
    
    /* 容器样式 */
    .layui-container {
        padding: 15px;
    }
    
    /* 表格工具栏 */
    .layui-table-tool {
        background-color: #f8f8f8;
    }
</style>
